<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" :width="800" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
import { computed, ref, unref, h } from 'vue';
import { BasicModal, useModalInner } from '@/components/Modal';
import { BasicForm, useForm } from '@/components/Form';
import { FormSchema } from '@/components/Form/src/types/form';
import { NumberList, MobileCardAdd } from '@/api/phoneAuth/phoneAuthList';
import { useMessage } from '@/hooks/web/useMessage';
import { Select, Button } from 'ant-design-vue';
import areaJsonData from './address.json'


// 可选号码列表
const numberOptions = ref<any[]>([]);

// 消息提示
const { createMessage } = useMessage();

// 套餐选项
const packageOptions = ref<any[]>([]);

// 是否正在刷新号码
const refreshing = ref(false);

// 添加响应式变量管理省市区选项
const provinceList = ref(areaJsonData);
const cityList = ref<any[]>([]);
const areaList = ref<any[]>([]);

// 加载可选号码列表
async function loadNumberList(packagecode: string) {
  try {
    const params = {
      region: '755', // 号码归属地
      packagecode, // 套餐编码
      page: 1,
      sysUserName: '', // 系统用户名，暂时为空
    };

    // 调用获取可选号码列表接口
    const res = await NumberList(params);

    // 处理接口返回结果
    if (res && res.infos && res.infos.length > 0) {
      numberOptions.value = res.infos.map(item => ({
        label: item.mobileno,
        value: item.mobileno
      }));
    } else {
      numberOptions.value = [];
      createMessage.warning('获取号码列表为空');
    }
  } catch (error) {
    createMessage.error('获取号码列表失败');
    numberOptions.value = [];
    throw error; // 重新抛出错误以便上层处理
  }
}

// 刷新号码列表
async function refreshNumbers(packagecode: string) {
  if (!packagecode) {
    createMessage.warning('请先选择套餐');
    return;
  }

  refreshing.value = true;
  try {
    await loadNumberList(packagecode);
    createMessage.success('号码列表已刷新');
  } finally {
    refreshing.value = false;
  }
}

// 表单配置
const formSchema: FormSchema[] = [
  {
    field: 'id',
    label: 'ID',
    component: 'Input',
    show: false,
  },
  {
    field: 'areaInfo',
    label: '号码归属地',
    component: 'Divider',
    colProps: { span: 24 },
  },
  {
    field: 'areaCode',
    label: '归属地编码',
    component: 'Input',
    defaultValue: '755',
    colProps: { span: 12 },
    componentProps: {
      disabled: true,
      placeholder: '请输入归属地编码',
    },
  },
  {
    field: 'areaName',
    label: '归属地名称',
    component: 'Input',
    defaultValue: '深圳',
    colProps: { span: 12 },
    componentProps: {
      disabled: true,
      placeholder: '请输入归属地名称',
    },
  },
  {
    field: 'packageInfo',
    label: '套餐信息',
    component: 'Divider',
    colProps: { span: 24 },
  },
  {
    field: 'mainprodid',
    label: '套餐编码',
    component: 'Select',
    required: true,
    colProps: { span: 24 },
    componentProps: ({ formModel }) => ({
      options: packageOptions.value.map(item => ({
        label: item.label,
        value: item.value,
      })),
      placeholder: '请选择套餐',
      onChange: async (e: any) => {
        const selected = packageOptions.value.find(item => item.value === e);
        if (selected) {
          const { price, desc, label } = selected;
          setFieldsValue({
            mainprodname: label,
            price: price,
            desc: desc,
            servnumber: undefined,
            areaCode: '755',
            areaName: '深圳'
          });

          await loadNumberList(e);
        }
      }
    }),
  },
  {
    field: 'mainprodname',
    label: '套餐名称',
    component: 'Input',
    colProps: { span: 24 },
    show: false,
  },
  {
    field: 'price',
    label: '套餐价格',
    component: 'Input',
    colProps: { span: 12 },
    componentProps: {
      disabled: true,
      addonAfter: '元',
    },
  },
  {
    field: 'desc',
    label: '套餐描述',
    component: 'Input',
    colProps: { span: 12 },
    componentProps: {
      disabled: true,
    },
  },
  {
    field: 'servnumber',
    label: '选择号码',
    component: 'Input',
    required: true,
    colProps: { span: 12 },
    rules: [{ required: true, message: '请选择号码' }],
    render: ({ model, field }) => {
      return h('div', { style: { display: 'flex', alignItems: 'center' } }, [
        h(Select, {
          options: numberOptions.value,
          value: model[field],
          style: { width: '100%' },
          placeholder: '请选择号码',
          disabled: isView.value,
          'onChange': (value) => {
            model[field] = value;
          }
        }),
        !isView.value ? h(Button, {
          type: 'link',
          loading: refreshing.value,
          onClick: () => refreshNumbers(model.mainprodid),
          style: { marginLeft: '8px' }
        }, { default: () => '换一批' }) : null
      ]);
    }
  },
  {
    field: 'userInfo',
    label: '用户信息',
    component: 'Divider',
    colProps: { span: 24 },
  },
  {
    field: 'userName',
    label: '用户姓名',
    component: 'Input',
    required: true,
    colProps: { span: 12 },
    rules: [{ required: true, message: '请输入用户姓名' }],
  },
  {
    field: 'cerNo',
    label: '身份证号',
    component: 'Input',
    colProps: { span: 12 },
    required: true,
    rules: [
      { required: true, message: '请输入身份证号' },
      { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号' },
    ],
    componentProps: {
      placeholder: '请输入身份证号',
    },
  },
  {
    field: 'telno',
    label: '联系电话',
    component: 'Input',
    required: true,
    colProps: { span: 12 },
    rules: [
      { required: true, message: '请输入联系电话' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' },
    ],
  },
  {
    field: 'addressInfo',
    label: '收货地址',
    component: 'Divider',
    colProps: { span: 24 },
  },
  {
    field: 'province',
    label: '省份',
    component: 'Select',
    required: true,
    colProps: { span: 8 },
    componentProps: {
      options: provinceList.value.map(item => ({
        label: item.name,
        value: item.name
      })),
      placeholder: '请选择省份',
      onChange: async (value: string) => {
        const selectedProvince = provinceList.value.find(p => p.name === value);
        cityList.value = selectedProvince ? selectedProvince.children || [] : [];
        
        // 使用updateSchema更新城市选项
        await updateSchema([
          {
            field: 'addressCity',
            componentProps: {
              options: cityList.value.map(city => ({
                label: city.name,
                value: city.name
              }))
            }
          },
          {
            field: 'addressArea',
            componentProps: {
              options: []
            }
          }
        ]);
        
        // 清空城市和区域选择
        setFieldsValue({
          addressCity: undefined,
          addressArea: undefined
        });
      }
    }
  },
  {
    field: 'addressCity',
    label: '城市',
    component: 'Select',
    required: true,
    colProps: { span: 8 },
    componentProps: {
      options: [],
      placeholder: '请选择城市',
      onChange: async (value: string) => {
        const province = getFieldsValue().province;
        const selectedProvince = provinceList.value.find(p => p.name === province);
        const selectedCity = selectedProvince?.children?.find(c => c.name === value);
        
        areaList.value = selectedCity ? selectedCity.children || [] : [];
        
        // 使用updateSchema更新区域选项
        await updateSchema([
          {
            field: 'addressArea',
            componentProps: {
              options: areaList.value.map(area => ({
                label: area.name,
                value: area.name
              }))
            }
          }
        ]);
        
        // 清空区域选择
        setFieldsValue({
          addressArea: undefined
        });
      }
    }
  },
  {
    field: 'addressArea',
    label: '区域',
    component: 'Select',
    required: true,
    colProps: { span: 8 },
    componentProps: {
      options: [],
      placeholder: '请选择区域'
    }
  },
  {
    field: 'address',
    label: '详细地址',
    component: 'InputTextArea',
    colProps: { span: 24 },
    rules: [{ required: true, message: '请输入详细地址' }],
    componentProps: {
      placeholder: '请输入详细地址',
      rows: 2,
    },
  },
  {
    field: 'inviterKey',
    label: '邀请人Key',
    component: 'Input',
    colProps: { span: 24 },
    componentProps: {
      placeholder: '请输入邀请人Key',
    },
  },
];

// 表单状态
const isView = ref(false);

// 使用组件
const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue, updateSchema }] = useForm({
  labelWidth: 120,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 24 },
  actionColOptions: {
    span: 24,
  },
  // 设置表单字段的公共属性
  fieldMapToTime: [],
  disabled: isView, // 在查看模式下禁用所有字段
});

// 获取当前表单值
const getValues = computed(() => {
  return getFieldsValue();
});

// 模态窗口
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  try {
    // 重置表单
    await resetFields();
    setModalProps({ confirmLoading: false });

    // 设置查看模式
    isView.value = !!data?.isView;

    // 设置套餐选项
    if (data?.packageOptions && Array.isArray(data.packageOptions)) {
      packageOptions.value = data.packageOptions;
    }

    // 处理记录数据
    if (data?.record) {
      // 默认赋值
      await setFieldsValue({
        ...data.record,
      });

      // 处理省市区数据
      if (data.record.province) {
        const selectedProvince = provinceList.value.find(p => p.name === data.record.province);
        if (selectedProvince) {
          cityList.value = selectedProvince.children || [];
          await updateSchema([
            {
              field: 'addressCity',
              componentProps: {
                options: cityList.value.map(city => ({
                  label: city.name,
                  value: city.name
                }))
              }
            }
          ]);

          if (data.record.addressCity) {
            const selectedCity = selectedProvince.children?.find(c => c.name === data.record.addressCity);
            if (selectedCity) {
              areaList.value = selectedCity.children || [];
              await updateSchema([
                {
                  field: 'addressArea',
                  componentProps: {
                    options: areaList.value.map(area => ({
                      label: area.name,
                      value: area.name
                    }))
                  }
                }
              ]);
            }
          }
        }
      }

      // 处理套餐数据
      if (data.record.mainprodid) {
        const selectedPackage = packageOptions.value.find(item => item.value === data.record.mainprodid);

        if (selectedPackage) {
          if (!data.record.price || !data.record.desc) {
            await setFieldsValue({
              mainprodname: selectedPackage.label,
              price: data.record.price || selectedPackage.price,
              desc: data.record.desc || selectedPackage.desc
            });
          }
        } else if (isView.value && data.record.mainprodname) {
          await setFieldsValue({
            price: data.record.price || '',
            desc: data.record.desc || ''
          });
        }

        // 仅在非查看模式时，加载可选号码列表
        if (!data?.isView) {
          try {
            await loadNumberList(data.record.mainprodid);
          } catch (err) {
            const errorMessage = err instanceof Error ? err.message : String(err);
            createMessage.error(`加载号码列表失败: ${errorMessage}`);
          }
        }
      }
    }

    // 如果是查看模式，禁用所有表单项
    if (unref(isView)) {
      setModalProps({ okButtonProps: { disabled: true } });
    }
  } catch (err) {
    const errorMessage = err instanceof Error ? err.message : String(err);
    console.error('模态框初始化错误:', err);
    createMessage.error(`初始化失败: ${errorMessage}`);
    
    // 关闭模态框
    closeModal();
  }
});

// 计算标题
const getTitle = computed(() => {
  return unref(isView) ? '查看移动卡申请详情' : '新增移动卡申请';
});

// 提交表单
async function handleSubmit() {
  try {
    setModalProps({ confirmLoading: true });
    const values = await validate();
    
    // 调用移动卡领取API
    await MobileCardAdd(values);

    createMessage.success('提交成功');
    closeModal();
    // 通知父组件刷新数据
    emit('reload');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}

// 定义事件
const emit = defineEmits(['reload']);
</script>

